<template>
  <div
    class="w-full h-full min-h-screen flex justify-center items-center bg-[var(--color-bg-1)] overflow-hidden bg-center bg-cover"
    :style="css"
  >
    <div
      class="flex justify-center items-center z-10 relative backdrop-blur-xs bg-[var(--color-bg-2)]/30 border border-[var(--color-border-1)]/30 shadow-lg"
    >
      <div class="w-96 h-96">
        <Lottie
          style="width: 100%; height: 100%"
          :params="{
            animationData: animationData,
          }"
          :get-animation-instance="
            (instance) => {
              instance?.setSpeed(0.3);
            }
          "
        />
      </div>
      <div class="p-6">
        <h1 class="text-center font-bold text-3xl">{{ $t('login.title') }}</h1>
        <a-form
          :model="formModel"
          :rules="formRules"
          size="large"
          auto-label-width
          @submit="handleSubmit"
        >
          <a-form-item hide-asterisk hide-label field="username">
            <a-input
              v-model="formModel.username"
              :placeholder="$t('login.username')"
            >
              <template #prefix>
                <icon-user />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item hide-asterisk hide-label field="password">
            <a-input-password
              v-model="formModel.password"
              autocomplete
              :placeholder="$t('login.password')"
            >
              <template #prefix>
                <icon-lock />
              </template>
            </a-input-password>
          </a-form-item>
          <a-form-item hide-asterisk hide-label field="code">
            <div class="flex gap-2">
              <a-input
                v-model="formModel.code"
                :placeholder="$t('login.captcha')"
                class="flex-1"
              >
                <template #prefix>
                  <icon-safe />
                </template>
              </a-input>
              <div
                class="captcha-image cursor-pointer rounded border"
                @click="getCaptcha"
              >
                <img
                  :src="captchaImage"
                  :alt="$t('login.captcha')"
                  class="h-full w-[120px] object-cover"
                />
              </div>
            </div>
          </a-form-item>
          <a-form-item no-style>
            <a-button type="primary" html-type="submit" long>
              {{ $t('login.loginButton') }}
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <div class="absolute top-3 right-3">
        <a-button
          shape="circle"
          @click="toggleTheme($event, colorMode === 'light' ? 'dark' : 'light')"
        >
          <icon-moon-fill v-if="colorMode === 'dark'" />
          <icon-sun-fill v-if="colorMode === 'light'" />
        </a-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import animationData from '@/assets/lottie/PepeStickerMusic.json';
import Lottie from '@/components/lottie.vue';
import { formRules } from '@/views/login/index';
import { Message } from '@arco-design/web-vue';
import type { ValidatedError } from '@arco-design/web-vue/es/form/interface';
import { getCaptchaImg } from '@/api/system/system';
import { login } from '@/api/system/user';
import type { Login } from '@/api/system/user';
import useTheme from '@/hooks/theme';
import { setToken } from '@/utils/auth';

defineOptions({
  name: 'LoginPage',
});
const router = useRouter();
const css = {
  backgroundImage: `url(${import.meta.env.VITE_LOGIN_BG})`,
};

const { colorMode, toggleTheme } = useTheme();

const formModel = ref<Login>({
  password: 'admin123',
  username: 'admin',
  code: '',
  uuid: '',
});
const captchaImage = ref('');
// 获取验证码
const getCaptcha = async () => {
  try {
    const res = await getCaptchaImg();
    const { result } = res.data;
    captchaImage.value = `data:image/png;base64,${result.img}`;
    formModel.value.uuid = result.uuid;
  } catch {
    Message.error('获取验证码失败');
  }
};

getCaptcha();

// 登录

const handleSubmit = async (data: {
  errors: Record<string, ValidatedError> | undefined;
}) => {
  if (data.errors) {
    Message.error('请填写完整信息');
  } else {
    try {
      await login(formModel.value).then((res) => {
        const { code, result, message } = res.data;
        console.log(code);
        if (code == 200) {
          setToken(result.token);
          // 登录
          Message.success('登录成功');
          const { redirect, ...othersQuery } = router.currentRoute.value.query;
          router.push({
            path: (redirect as string) || '/workplace',
            query: {
              ...othersQuery,
            },
          });
        } else {
          getCaptcha();
          Message.error(message || '登录失败');
        }
      });
    } catch (error) {
      console.error(error);
      getCaptcha();
    }
  }
};
</script>
